<template>
  <!-- 工作票 -->
  <a-modal
    v-model:open="visible"
    title="工作票"
    @ok="handleOk"
    class="addStation"
    destroyOnClose
    :width="860"
    @cancel="cancel"
    centered
  >
    <DownloadOutlined
      v-hasPermission="'ticketDownload'"
      class="downloadBtn"
      @click="handleDownload"
    />
    <div ref="file"></div>
    <template #footer>
      <div class="footerBar">
        <a-button key="back" @click="cancel">关闭</a-button>
      </div>
    </template>
  </a-modal>
</template>
<script setup>
// 
import axios from "axios"

import storage from "@/utils/storage"
import { renderAsync } from "docx-preview"
import Docxtemplater from "docxtemplater"
import JSZip from "jszip"
import JSZipUtils from "jszip-utils"
import { saveAs } from "file-saver"
import { isNumber, cloneDeep, clone } from "lodash-es"
import {
  WORK_TICKET_FIELDS,
  WORK_TYPE_LIST,
  HARM_LIST,
  DEVICE_LIST,
  PROTECT_EQUIPMENT,
} from "@/constants/workOrder"
const props = defineProps({
  ticketVisible: {
    type: Boolean,
    default: false,
  },
  ticketRowData: {
    type: Object,
  },
  infoData: {
    type: Object,
  },
  stationtList: {
    type: Array,
  },
})
const visible = ref(props.ticketVisible)
const emits = defineEmits(["update:ticketVisible", "getOrderList"])
const file = ref(null)
const checkIcon = "\u2611"
const normalIcon = "\u2610"
const form = ref({
  name: checkIcon,
  packWork: checkIcon,
})
const renderConfig = {
  className: "docx", //默认和文档样式类的类名/前缀
  inWrapper: true, //启用围绕文档内容呈现包装器
  ignoreWidth: false, //禁用页面的渲染宽度
  ignoreHeight: false, //禁用页面的渲染高度
  ignoreFonts: false, //禁用字体渲染
  breakPages: true, //在分页符上启用分页
  ignoreLastRenderedPageBreak: true, //在lastRenderedPageBreak元素上禁用分页
  experimental: false, //启用实验功能（制表符停止计算）
  trimXmlDeclaration: true, //如果为true，则在解析之前将从xml文档中删除xml声明
  useBase64URL: false, //如果为true，图像、字体等将转换为base 64 URL，否则使用URL.createObjectURL
  useMathMLPolyfill: false, //包括用于铬、边等的MathML多填充。
  showChanges: false, //启用文档更改的实验渲染（插入/删除）
  debug: false, //启用额外的日志记录
}
const fileOutput = ref(null)

watch(
  () => props.ticketVisible,
  async (val) => {
    visible.value = val
    if (val) {
      await handleDocx()
      fileRender(fileOutput.value)
    }
  }
)
const handleDocx = () => {
  let handleTicketData = {
    ...cloneDeep(props.infoData),
    ...props.ticketRowData,
  }
  WORK_TYPE_LIST.forEach((item, index) => {
    if (handleTicketData.workType.split(",").includes(index.toString())) {
      handleTicketData[`A${index}`] = checkIcon
    } else {
      handleTicketData[`A${index}`] = normalIcon
    }
  })
  HARM_LIST.forEach((item, index) => {
    if (
      handleTicketData.hazardIdentification
        .split(",")
        .includes(index.toString())
    ) {
      handleTicketData[`B${index}`] = checkIcon
    } else {
      handleTicketData[`B${index}`] = normalIcon
    }
  })
  handleTicketData.B18 = handleTicketData.hazardIdentificationOther
  DEVICE_LIST.forEach((item, index) => {
    if (
      handleTicketData.workSafetyMeasure.split(",").includes(index.toString())
    ) {
      handleTicketData[`C${index}`] = checkIcon
    } else {
      handleTicketData[`C${index}`] = normalIcon
    }
  })
  handleTicketData.C12 = handleTicketData.workSafetyMeasureOther
  PROTECT_EQUIPMENT.forEach((item, index) => {
    if (
      handleTicketData.protectiveEquipment.split(",").includes(index.toString())
    ) {
      handleTicketData[`D${index}`] = checkIcon
    } else {
      handleTicketData[`D${index}`] = normalIcon
    }
  })
  handleTicketData.D9 = handleTicketData.protectiveEquipmentOther
  // 安全工作方案附件
  handleTicketData.safetyPlanFileIds = handleTicketData.safetyPlanFileIds
    ? "是"
    : "否"
  // 图纸附件
  handleTicketData.drawingFileIds = handleTicketData.drawingFileIds
    ? "是"
    : "否"
  // 其他附件
  handleTicketData.otherAttachFileIds = handleTicketData.otherAttachFileIds
    ? "是"
    : "否"

  // 作业申请人时间 年月日时

  handleTicketData.createTimeY = handleTicketData.createTime
    .split(" ")[0]
    .split("-")[0]
  handleTicketData.createTimeM = handleTicketData.createTime
    .split(" ")[0]
    .split("-")[1]
  handleTicketData.createTimeD = handleTicketData.createTime
    .split(" ")[0]
    .split("-")[2]
  handleTicketData.createTimeH = handleTicketData.createTime
    .split(" ")[1]
    .split(":")[0]
  // 作业申请人
  handleTicketData.dealUserName = handleTicketData?.createUserName || ""
  // 作业批准人
  handleTicketData.createUserNameAppr =
    handleTicketData?.approve?.createUserName || ""
  handleTicketData.createUserNameY =
    handleTicketData?.approve?.createTime.split(" ")[0].split("-")[0] || ""
  handleTicketData.createUserNameM =
    handleTicketData?.approve?.createTime.split(" ")[0].split("-")[1] || ""
  handleTicketData.createUserNameD =
    handleTicketData?.approve?.createTime.split(" ")[0].split("-")[2] || ""
  handleTicketData.createUserNameH =
    handleTicketData?.approve?.createTime.split(" ")[1].split(":")[0] || ""

  // 受影响相关方
  handleTicketData.affectedStakeholders =
    handleTicketData.affectedStakeholders || ""

  // 受影响相关方共同签署 有效期
  handleTicketData.operationDateY = handleTicketData.operationDate
    .split(" ")[0]
    .split("-")[0]
  handleTicketData.operationDateM = handleTicketData.operationDate
    .split(" ")[0]
    .split("-")[1]
  handleTicketData.operationDateD = handleTicketData.operationDate
    .split(" ")[0]
    .split("-")[2]
  handleTicketData.operationStartDate =
    handleTicketData.operationStartDate.split(":")[0]
  handleTicketData.operationEndDate =
    handleTicketData.operationEndDate.split(":")[0]

  // 作业项目
  handleTicketData.companyName = handleTicketData?.companyName || ""
  // 图纸说明
  handleTicketData.drawingDesc = handleTicketData?.drawingDesc || ""
  // 许可证的关闭
  handleTicketData.dealUserNameClose = handleTicketData.dealUserNameClose || ""
  handleTicketData.affectedStakeholdersClose =
    handleTicketData?.affectedStakeholdersClose || ""
  handleTicketData.createTimeCloseY =
    handleTicketData?.createTimeClose?.split(" ")[0].split("-")[0] || ""
  handleTicketData.createTimeCloseM =
    handleTicketData?.createTimeClose?.split(" ")[0].split("-")[1] || ""
  handleTicketData.createTimeCloseD =
    handleTicketData?.createTimeClose?.split(" ")[0].split("-")[2] || ""
  handleTicketData.createTimeCloseH =
    handleTicketData?.createTimeClose?.split(" ")[1].split(":")[0] || ""

  handleTicketData.isCloseDealLog = handleTicketData.closeDealLog
    ? checkIcon
    : normalIcon
  handleTicketData.closeRemark = handleTicketData?.closeDealLog?.remark || ""
  handleTicketData.closeCreateUserName =
    handleTicketData?.closeDealLog?.createUserName || ""

  handleTicketData.closeCreateUserNameY =
    handleTicketData?.closeDealLog?.createTime?.split(" ")[0].split("-")[0] ||
    ""
  handleTicketData.closeCreateUserNameM =
    handleTicketData?.closeDealLog?.createTime?.split(" ")[0].split("-")[1] ||
    ""
  handleTicketData.closeCreateUserNameD =
    handleTicketData?.closeDealLog?.createTime?.split(" ")[0].split("-")[2] ||
    ""
  handleTicketData.closeCreateUserNameH =
    handleTicketData?.closeDealLog?.createTime?.split(" ")[1].split(":")[0] ||
    ""

  // 许可证的延期
  handleTicketData.dealUserNameDelay = handleTicketData?.dealUserNameDelay || ""
  handleTicketData.affectedStakeholdersDelay =
    handleTicketData?.affectedStakeholdersDelay || ""
  handleTicketData.delayRemark =
    handleTicketData?.workTicketDealLogDto?.remark || ""
  handleTicketData.delayCreateTimeY =
    handleTicketData?.delayApprove?.createTime?.split(" ")[0].split("-")[0] ||
    ""
  handleTicketData.delayCreateTimeM =
    handleTicketData?.delayApprove?.createTime?.split(" ")[0].split("-")[1] ||
    ""
  handleTicketData.delayCreateTimeD =
    handleTicketData?.delayApprove?.createTime?.split(" ")[0].split("-")[2] ||
    ""
  handleTicketData.delayStarH =
    handleTicketData?.delayApprove?.delayStartDate?.split(":")[0] || ""
  handleTicketData.delayEndH =
    handleTicketData?.delayApprove?.delayEndDate?.split(":")[0] || ""

  // 许可证的延期批准 年月日和上面的延期申请一样
  handleTicketData.delayApproveUser =
    handleTicketData?.delayApprove?.createUserName || ""
  handleTicketData.delayApproveH =
    handleTicketData?.delayApprove?.createTime?.split(" ")[1].split(":")[0] ||
    ""

  return new Promise((resolve, reject) => {
    // 读取并获得模板文件的二进制内容
    JSZipUtils.getBinaryContent(`stationLicense.docx`, (error, content) => {
      // 处理错误
      if (error) {
        return reject(error)
      }
      let zip = new JSZip(content)
      let doc = new Docxtemplater()
      doc.loadZip(zip)
      // 设置模板变量的值
      doc.setData({
        ...handleTicketData,
      })
      try {
        doc.render()
      } catch (error) {
        // 处理渲染错误
        let e = {
          message: error.message,
          name: error.name,
          stack: error.stack,
          properties: error.properties,
        }
        console.log(JSON.stringify({ error: e }))
        return reject(error) // 拒绝 Promise
      }
      let out = doc.getZip().generate({
        type: "blob",
        mimeType:
          "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
      })
      fileOutput.value = out
      resolve(out)
    })
  })
}
const handleDownload = async () => {
  await handleDocx()
  saveAs(fileOutput.value, "新巨能电站作业许可证.docx")
}
const fileRender = (event) => {
  renderAsync(event, file.value, null, renderConfig)
}
const cancel = () => {
  emits("update:ticketVisible", false)
}
const loading = ref(false)
defineExpose({ handleDownload })
</script>

<style lang="less" scoped>
.footerBar {
  text-align: center;
  margin-top: 30px;
}
.downloadBtn {
  position: absolute;
  right: 37px;
  top: 55px;
  font-size: 20px;
  cursor: pointer;
}
</style>
